package com.hxy.pay.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.hxy.order.domain.AdoptOrder;
import com.hxy.order.domain.ProductOrder;
import com.hxy.order.service.IAdoptOrderService;
import com.hxy.order.service.IProductOrderService;
import com.hxy.pay.config.AlipayConfig;
import com.hxy.pay.constants.PayConstants;
import com.hxy.pay.domain.AlipayInfo;
import com.hxy.pay.domain.PayBill;
import com.hxy.pay.service.IAlipayInfoService;
import com.hxy.pay.service.IPayBillService;
import com.hxy.quartz.constant.JobConstants;
import com.hxy.quartz.service.IQuartzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;



@RestController
public class AlipayController {
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IAlipayInfoService alipayInfoService;
    @Autowired
    private IAdoptOrderService adoptOrderService;
    @Autowired
    private IProductOrderService productOrderService;
    @Autowired
    private IQuartzService quartzService;
    @PostMapping("/notify")
    public void changeState(HttpServletRequest request){
        try {
            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            String unionPaysn = params.get("out_trade_no");
            PayBill payBill = payBillService.loadByUnionPaySn(unionPaysn);
            AlipayInfo alipayInfo = alipayInfoService.getByShopId(payBill.getShop_id());

            //支付宝的公钥 - AlipayInfo - shop_id - PayBill - unionPaysn
            //先根商家的私有解密，确认身份 - 解密
            boolean signVerified = AlipaySignature.rsaCheckV1(params,
                    alipayInfo.getAlipay_public_key(),
                    AlipayConfig.charset,
                    AlipayConfig.sign_type); //调用SDK验证签名
            if(signVerified) {//验证成功
                //商户订单号 = UnionPaySn
                String out_trade_no = unionPaysn;
                //支付宝交易号
                String trade_no = request.getParameter("trade_no");
                //交易状态
                String trade_status = request.getParameter("trade_status");

                if(trade_status.equals("TRADE_FINISHED")){//确认之后
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                }else if (trade_status.equals("TRADE_SUCCESS")){ //支付成功之后

                    payBill.setState(1);//已支付
                    payBill.setUpdateTime(new Date());
                    payBillService.update(payBill);//改支付单状态

                    String businessType = payBill.getBusinessType();
                    System.out.println("Type" + businessType);

                    if(businessType.equals(PayConstants.BUSINESS_TYPE_ADOPT)){//确认是领养订单，因为其他订单有可能有一样的id值
                        Long adoptOrderId = payBill.getBusinessKey();
                        AdoptOrder adoptOrder = adoptOrderService.findOne(adoptOrderId);
                        adoptOrder.setState(1);
                        //修改订单的状态
                        adoptOrderService.update(adoptOrder);
                        //支付成功取消定时任务
                        quartzService.del(JobConstants.OVER_TIME_NO_PAY_ADOPT + out_trade_no);
                        System.out.println("支付成功删除定时任务...");
                        //@TODO 1.取消任务马上上架  2.后台管理手动上架
                    }
                    else if(businessType.equals(PayConstants.BUSINESS_TYPE_PRODUCT)){
                        Long productOrderId = payBill.getBusinessKey();
                        ProductOrder productOrder = productOrderService.findOne(productOrderId);
                        productOrder.setState(1);
                        //修改订单的状态
                        productOrderService.update(productOrder);
                        //支付成功取消定时任务
                        quartzService.del(JobConstants.OVER_TIME_NO_CONFIRM_PRODUCT + out_trade_no);
                        System.out.println(out_trade_no);
                        System.out.println("支付成功删除定时任务...");
                        //@TODO 1.取消任务马上上架  2.后台管理手动上架
                    }
                }
            }else {//验证失败
                //调试用，写文本函数记录程序运行情况是否正常
                //String sWord = AlipaySignature.getSignCheckContentV1(params);
                //AlipayConfig.logResult(sWord);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


